package cn.kgc.springmvc.day04.interceptors;

import cn.hutool.json.JSONUtil;
import cn.kgc.springmvc.day04.response.ResponseResult;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @author 课工场
 * @date 2024/7/23
 * @description     拦截器  HandlerInterceptor
 */
public class LoginInterceptor implements HandlerInterceptor {

    //   执行时机    在请求到达具体的handler之前执行    /user/add      filter  chain.doFilter(req,resp)
    //  true   放行请求   false  拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //  session  username
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");

        if (username==null){
            //  响应数据给浏览器
            ResponseResult responseResult = new ResponseResult();
            responseResult.setCode(401);
            responseResult.setMessage("请认证后访问...");

            // 响应json格式的数据  浏览器
            response.setContentType("application/json;charset=utf-8");
            //  java  ->  json
            String jsonStr = JSONUtil.toJsonStr(responseResult);
            System.out.println("jsonStr = " + jsonStr);

            PrintWriter writer = response.getWriter();
            writer.write(jsonStr);
            writer.close();

            return  false;
        }

        return true;
    }
}
